
import React from 'react'
import $ from 'jquery'
import _ from 'underscore'
import Modal from 'lib/components/Modal.jsx'
import dashboardsApi from '../apis/dashboards'
import widgetsApi from '../apis/widgets'
import {saveWidgetApi} from '../apis/validApis/widget'
import {saveDashboardApi} from '../apis/validApis/dashboard'
import {Success,Info,Warning} from 'lib/components/Notify.jsx'

const dashboardsGet = dashboardsApi()


export class NewWidgetModal extends Modal {
  constructor(props){
    super(props);
    this.state = {
      msg:'',
      dashboards:props.dashboards
    }
    this.addWidget = this.addWidget.bind(this)
    this.addDashboard = this.addDashboard.bind(this)
    this.cleanMsg = this.cleanMsg.bind(this)
  }
  cleanMsg(){
    this.setState({
      msg:''
    })
  }
  addDashboard(){
    var _this = this
    if(this.state.saving){
      return ;
    }
    saveDashboardApi({
      name:$(this.refs.dashboardTitle).val()
    }).post().then((newDashboard) => {
      this.setState({
        saving:false,
        dashboards:this.state.dashboards.concat([newDashboard])
      })
    },(err) => {
      this.setState({
        saving:false,
        msg:err.msg||err.message
      })
    },() => {
      this.setState({
        saving:true
      })
    })
  }
  addWidget(){
    var _this = this
    if(this.state.saving){
      return ;
    }
    var dashboardId = $(this.refs.dashboard).val()
      , title = $(this.refs.widgetTitle).val()
    let widgetGet = widgetsApi({
      dashboardId:dashboardId
    })
    widgetGet.fetch().then(function(widgets){
      if(widgets.length>=8){
        return _this.setState({
          saving:false,
          msg:'仪表盘最多只能添加8个图表'
        })
      }
      return saveWidgetApi({
        dashboardId:dashboardId,
        name:title,
        requestParam:JSON.stringify(_this.props.widget.params),
        requestUrl:_this.props.widget.url,
        config:JSON.stringify(_.extend({
          viewKey:_this.props.widget.params.viewKey,
          appName:BlueWare.appName,
          appId:BlueWare.appId,
          appVersion:BlueWare.appversion||undefined,
          appVersionId:BlueWare.appVersionId||undefined
        },_this.props.config))
      }).post().then(function(result){
        if(result.id){
          Success(<p>
            添加成功，
            <a href={BlueWare.pageUrlPrefix+'/dashboard/'+dashboardId}>进入仪表盘查看</a>
          </p>)
          _this.close()
        }
      },function(err){
        _this.setState({
          saving:false,
          msg:err.msg||err.message
        })
      })
    },function(){
      _this.setState({
        saving:true
      })
    })
  }
  renderHeader(){
    return (
      <h4>添加到仪表盘</h4>
    )
  }
  renderBody(){
    return (
      <div className="form-group horizontal">
        <ul>
          {
            this.state.dashboards.length?(
              <li>
                <label className="control-label">选择仪表盘</label>
                <select className="select" ref="dashboard" onChange={this.cleanMsg}>
                  {
                    this.state.dashboards.map(function(dashboard, index){
                      return (
                        <option key={index} value={dashboard.id}>{dashboard.name}</option>
                      )
                    })
                  }
                </select>
              </li>
            ):(
              <li>
                <label className="control-label">请先添加一个仪表盘</label>
                <input className="input-text" ref="dashboardTitle" onChange={this.cleanMsg} />
              </li>
            )
          }
          {
            this.state.dashboards.length?(
              <li>
                <label className="control-label">图表标题</label>
                <input className="input-text" ref="widgetTitle" defaultValue={this.props.widget.widgetName} onChange={this.cleanMsg} />
              </li>
            ):null
          }
          {
            this.state.msg?(
              <li>
                <label className="control-label"></label>
                <span className="msg-error">{this.state.msg}</span>
              </li>

            ):null
          }
        </ul>
      </div>
    )
  }
  renderFooter(){
    return (
      <div>
        {
          this.state.saving?(
            <span>保存中...</span>
          ):(
            this.state.dashboards.length?(
              <button className="btn-green"
                onClick={this.addWidget}
                type="button">
                添加
              </button>
            ):(
              <button className="btn-green"
                onClick={this.addDashboard}
                type="button">
                添加
              </button>
            )

          )
        }
      </div>
    )
  }
}
function addWidgetMixin(api,title,extra){
  function showModal(){
    dashboardsGet.fetch().then(function(dashboards){
      NewWidgetModal.mount({
        dashboards:dashboards,
        widget:{
          url:api.lastUrl,
          params:api.lastParams,
          widgetName:BlueWare.appName + (BlueWare.appversion?' '+ BlueWare.appversion:'') + ' - ' + title
        },
        config:extra
      })
    })
  }
  return (
    <a data-tip="添加到仪表盘" key={ Math.random() } data-place="top" className="iconfont add-dashboard" href="javascript:;" onClick={showModal}>&#xe629;</a>
  )

}
export default addWidgetMixin
